﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SmartMD.DataModel.Entity;
using SmartMD.DataAccess.Service;
using System.Collections.ObjectModel;
using SmartMD.Manager.Common;
using System.Xml;
using SmartMD.Manager.Utils;
using Duoease.ContainerModel.Utils;
using Techstar.Dialog;

namespace SmartMD.Manager.Container
{
    /// <summary>
    /// Interaction logic for NewContainerDialog.xaml
    /// </summary>
    public partial class NewContainerDialog : Window
    {
        private string _rootId = null;
        private int _fridgeMaxNum = 0;
        private int _shelfMaxNum = 0;
        private int _boxMaxNum = 0;
        private ObservableCollection<ContainerModelEntity> _modelEntityList = null;
        public ObservableCollection<ContainerModelEntity> ModelEntityList
        {
            get {
                if (_modelEntityList == null)
                {
                    _modelEntityList = DataServiceManager.ContainerModelService.loadAllContainerModels();
                }
                return _modelEntityList;
            }
        }

        public NewContainerDialog()
        {
            InitializeComponent();
        }

        public NewContainerPanel Owner;

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            string styleXml = null;
            for (int i = 0; i < ModelEntityList.Count; i++)
            {
                if (this.txtType.Text == ModelEntityList[i].Name)
                {
                    styleXml = CompressionHelper.DeCompressToString(ModelEntityList[i].StyleFile);
                    break;
                }
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(styleXml);
            XmlNode node = doc.SelectSingleNode("Container");
            if (node != null)
            {
                string specification = node.Attributes["Specification"].Value.ToString();
                string[] tmpArr = specification.Split('-');
                _fridgeMaxNum = int.Parse(tmpArr[0].Substring(0, 1))* int.Parse( tmpArr[0].Substring(1, 1));
                _shelfMaxNum = int.Parse(tmpArr[1].Substring(0, 1)) * int.Parse(tmpArr[1].Substring(1, 1));

                _boxMaxNum = ModelUtil.GetCodeValue(tmpArr[2].Substring(0, 1)) * ModelUtil.GetCodeValue(tmpArr[2].Substring(1, 1));//int.Parse(tmpArr[2].Substring(1, 1));
            }
            //新建冰箱节点
            if (this.txtName.Text == null || this.txtName.Text == "")
            {
                TaskDialogEx.Warning("提示信息", "请输入容器名称！");
                return;
            }
            ContainerEntity entity = new ContainerEntity();
            entity.Id = System.Guid.NewGuid().ToString(); //System.DateTime.Now.ToString("yyyyMMddHHmmss");
            _rootId = entity.Id;
            entity.SiteCode = this.txtName.Text;
            entity.ModelType = this.txtType.Text;
            entity.Description = this.txtDesc.Text;
            entity.State = DataModel.RecordState.Normal;
            entity.RootId = "NULL";
            entity.RemainingCapacity = _fridgeMaxNum * _shelfMaxNum * _boxMaxNum;
            entity.WholeCapacity = _fridgeMaxNum * _shelfMaxNum * _boxMaxNum;
            DataServiceManager.ContainerService.SaveOrUpdateContainer(entity);
            if (this.Owner != null)
            {
                this.Owner.ContainerEntitys.Add(entity);
            }
            
            if (node != null)
            {               
                CreateContainerEntity(node, entity.SiteCode, entity.ModelType, entity.Id);
            }
            //关闭窗口
            this.Close();
        }
        /***
         * 功能:保持容器每个元素节点
         * 
         * */
        private void CreateContainerEntity(XmlNode node , string containerName, string modelType, string pId)
        {
            string id;

            foreach (XmlNode xn in node)//遍历
            {
                //保存容器节点
                id = containerName + xn.Attributes["ID"].Value.ToString();
                if (id == containerName) //去掉容器实体
                    continue;
               ContainerEntity parentContainer = null;
                int lastindex = id.LastIndexOf("-");               
                if (lastindex > 0)
                {
                    string sitecode = null;
                    sitecode = id.Substring(0, lastindex);
                    parentContainer = DataServiceManager.ContainerService.GetContainerBySitecode(sitecode);
                }       
                ContainerEntity containerEntity = new ContainerEntity();
                containerEntity.Id = System.Guid.NewGuid().ToString();
                containerEntity.SiteCode = id;
                containerEntity.ParentId = parentContainer.Id;
                containerEntity.ModelType = modelType;
               
                if (id.Split('-').Length == 2)
                {
                    containerEntity.RemainingCapacity = _shelfMaxNum * _boxMaxNum;
                    containerEntity.WholeCapacity = _shelfMaxNum * _boxMaxNum;
                }
                else if (id.Split('-').Length == 3)
                {
                    containerEntity.RemainingCapacity = _boxMaxNum;
                    containerEntity.WholeCapacity = _boxMaxNum;
                }
                containerEntity.Name = id;
                containerEntity.RootId = _rootId;

                DataServiceManager.ContainerService.SaveOrUpdateContainer(containerEntity);
                //保存格子元素
                string[] tmpStrArr = id.Split('-');
                if (tmpStrArr.Length >= 3)
                {

                    ContainerEntity boxCell;
                    int boxColumn = int.Parse(xn.Attributes["Column"].Value.ToString());
                    int boxRow = int.Parse(xn.Attributes["Row"].Value.ToString());
                    for (int j = 1; j <= boxRow; j++)
                    {
                            for (int k = 1; k <= boxColumn; k++)
                            {
                                boxCell = new ContainerEntity();
                                boxCell.SiteCode = id + "-" + ModelUtil.GetLetter(j).ToString() + ModelUtil.GetCodeNo(k);//k.ToString();
                                boxCell.Id = System.Guid.NewGuid().ToString();
                                boxCell.ParentId = containerEntity.Id;
                                boxCell.ModelType = modelType;
                                boxCell.RemainingCapacity = 1;
                                boxCell.WholeCapacity = 1;
                                boxCell.Name = id + "-" + ModelUtil.GetLetter(j).ToString() + ModelUtil.GetCodeNo(k);//k.ToString();
                                boxCell.RootId = _rootId;

                                DataServiceManager.ContainerService.SaveOrUpdateContainer(boxCell);
                            }
                    }
                }
            }
        }
    

        private void cmbContainerType_Initialized(object sender, EventArgs e)
        {          
            if (ModelEntityList == null)
                return;
            
            List<ComboBoxValueItem> datasource = new List<ComboBoxValueItem>();

            for (int i = 0; i < ModelEntityList.Count; i++)
            {
                ContainerModelEntity item = ModelEntityList[i];
                datasource.Add(new ComboBoxValueItem { Name = item.Name, Value = item.Id });
            }

            (sender as ComboBox).ItemsSource = datasource;  
        }

        public object ObservableCollection { get; set; }
    }
}
